package com.project.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.server.exception.BusinessException;
import com.project.server.mapper.DiningTableMapper;
import com.project.server.mapper.DishMapper;
import com.project.server.model.Restaurant;
import com.project.server.mapper.RestaurantMapper;
import com.project.server.service.DiningTableService;
import com.project.server.service.DishService;
import com.project.server.service.RestaurantService;
import com.project.server.vo.DiningTableVO;
import com.project.server.vo.DishVO;
import com.project.server.vo.RestaurantVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.List;

@Service
public class RestaurantServiceImpl implements RestaurantService {

    @Autowired
    private RestaurantMapper restaurantMapper;

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DiningTableMapper diningTableMapper;

    @Override
    public Page<Restaurant> page(Integer pageNum, Integer pageSize, String name) {
        Page<Restaurant> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Restaurant> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like(Restaurant::getName, name);
        }
        wrapper.orderByDesc(Restaurant::getStatus);
        return restaurantMapper.selectPage(page, wrapper);
    }


    @Override
    public void save(Restaurant restaurant) {
        restaurantMapper.insert(restaurant);
    }

    @Override
    public void update(Restaurant restaurant) {
        restaurantMapper.updateById(restaurant);
    }

    @Override
    public void removeById(Long id) {
        restaurantMapper.deleteById(id);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Restaurant restaurant = new Restaurant();
        restaurant.setId(id);
        restaurant.setStatus(status);
        restaurantMapper.updateById(restaurant);
    }

    @Override
    public List<Restaurant> queryAll() {
        return restaurantMapper.selectList(null);
    }

    @Override
    public RestaurantVO getDetail(Long id) {
        // 获取餐厅基本信息
        Restaurant restaurant = restaurantMapper.selectById(id);
        if (restaurant == null) {
            throw new BusinessException("餐厅不存在");
        }

        RestaurantVO vo = new RestaurantVO();
        BeanUtils.copyProperties(restaurant, vo);

        // 获取餐厅菜品
        List<DishVO> dishes = dishMapper.getByRestaurantId(id);
        vo.setDishes(dishes);

        // 获取餐厅餐桌
        List<DiningTableVO> tables = diningTableMapper.getByRestaurantId(id);
        vo.setTables(tables);

        return vo;
    }
}
